#!/bin/bash

DIR=`dirname $0`

echo $0

if [[ -z $1 ]] || [[ -z $2 ]]; then
  echo "Usage:  build git_url appname"
  exit 1
fi

GIT=$1
shift
APP=$1
shift

if [[ -z $OS_USERNAME ]]; then
  echo 'OpenStack credentials not passed via ENV. hunting for openrc.'
  [[ -f ./openrc ]] && . ./openrc
  [[ -f ~/devstack/openrc ]] && . ~/devstack/openrc
fi

glance image-list 2> /dev/null > /dev/null
if [ $? != 0 ]; then
  echo 'cannot talk to glance. check your OpenStack credentials'
  exit 1
fi


ID=`< /dev/urandom tr -dc A-Z-a-z-0-9 | head -c${rnd:-32};echo;`

echo Build ID - $ID

APP_DIR=/opt/solum/apps/$APP
BUILD_DIR=/opt/solum/apps/$APP/build
IMAGE_DIR=/opt/solum/apps/$APP/image

mkdir -p $BUILD_DIR
mkdir -p $IMAGE_DIR

[[ -d $BUILD_DIR ]] && rm -rf $BUILD_DIR

mkdir -p $BUILD_DIR

cp -R $DIR/* $BUILD_DIR

echo "$APP git /app $GIT" > $BUILD_DIR/elements/cedarish/source-repository-app

echo "create image"

export PATH=$PATH:/opt/disk-image-builder/bin

export ELEMENTS_PATH=$BUILD_DIR/elements

disk-image-create --no-tmpfs -a amd64 vm ubuntu -o $IMAGE_DIR/$ID.qcow2 cedarish

if [[ ! -f $IMAGE_DIR/$ID.qcow2 ]]; then
  echo something went wrong building image
  exit 1
fi

echo image: /tmp/$ID.qcow2

glance image-list 2> /dev/null > /dev/null
if [[ $? == 0 ]]; then
  echo it would appear I know how to talk to glance
  echo therefore I will attempt to upload your image
  glance image-create --name $APP --disk-format qcow2 --container-format bare --file $IMAGE_DIR/$ID.qcow2
else
  echo I cannot talk to glance your image is here: $IMAGE_DIR/$ID.qcow2
  echo Try this: glance image-create --name $APP --disk-format qcow2 --container-format bare --file $IMAGE_DIR/$ID.qcow2
  exit 1
fi

echo I will try and create you security groups

nova secgroup-create $APP "allow ssh/web to instance"
nova secgroup-add-rule $APP tcp 22 22 0.0.0.0/0
nova secgroup-add-rule $APP tcp 5000 5000 0.0.0.0/0

nova keypair-add ${APP}_key > ${APP_DIR}/key.priv
chmod 0600 ${APP_DIR}/key.priv

cp ${DIR}/user-data.txt ${APP_DIR}/user-data.txt

echo modify ${DIR}/user-data.txt to set any needed ENV variables
echo boot your app like this
echo nova boot --flavor=2 --image=${APP} --security-groups=${APP} \
               --key-name=${APP}_key --user-data=${APP_DIR}/user-data.txt ${APP}01
